// 如果打开页面时,没有获取到启动信息,则先获取启动信息,才能去请求页面
import store from "../store"
import ajax from './ajax.js'
import config from '../projectInfo.js'
import getIcons from './getIcons.js'
import getAppStartPage from './getAppStartPage.js'
import fileManage from './fileManage.js'
import saveFile from './saveFile.js'
import vuexSave from './vuexSave.js'
import terminalCode from './terminalCode.js'

let fs = fileManage.fs,ifFileManage = fileManage.ifFileManage,userDataPath = fileManage.userDataPath;
const downSkin = (skin_version, skinUrl) => {
	return new Promise((resolve, reject) => {
		if(!skinUrl){
			reject()
			return
		}
		// 一、下载皮肤
		uni.downloadFile({
			url: skinUrl,
			success(res) {
				console.log('downloadFile-success', res);
				saveFile(res.tempFilePath,'skin.png').then(res=>{
					getSkinSize(res.savedFilePath).then(wh=>{
						// #ifdef MP-WEIXIN
						// 下载并保存好皮肤图片后,写入一个本地文件记录皮肤版本和尺寸，便于下次启动时读取
						fs.writeFile({
							filePath: `${userDataPath}/skin_info.txt`,
							data: skin_version + ',' + wh,
							encoding: 'utf8',
							success(res) {
								console.log('writeFile-success', res)
								resolve()
							},
							fail(res) {
								console.log('writeFile-fail', res)
								reject()
							}
						})
						// #endif
						// #ifdef MP-ALIPAY
						// 将皮肤版本好存入vuex及缓存
						vuexSave("$skinVersion", skin_version)
						resolve()
						// #endif
					},()=>{
						reject()
					})
				},()=>{
					reject()
				})
			},
			fail(res) {
				console.log('downloadFile-fail', res);
				reject()
			}
		})
	})
}
// 获取图片的尺寸并保存到store中
const getSkinSize = skinUrl => {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src: skinUrl,
			success: image => {
				console.log('获取皮肤图片尺寸成功,皮肤尺寸为', image.width, image.height);
				vuexSave('$skinUrl', skinUrl);
				vuexSave('$skinW', image.width);
				vuexSave('$skinH', image.height);
				resolve(image.width + ',' + image.height);
			},
			fail() {
				console.log('获取皮肤图片失败,皮肤路径为', skinUrl);
				reject()
			}
		})
	})
}
export default () => {
	return new Promise((resolve, reject) => {
		// 每次启动程序只需要查询一次项目信息，根据$version>0来判断是否查询过
		if (store.state.$version > 0) {
			resolve()
			return
		}
		uni.showLoading({
			title: '加载项目资源中'
		});
		// 查询项目信息
		new Promise((resolve, reject) => {
			if (config.development === 'prod') {
				return ajax({
					url: 'https://version.krtservice.com/' + store.state.$tag + '.json',
					ifFile: true,
					method: 'get'
				}).then(res => {
					if (res.code === store.state.$tag) {
						resolve(res)
					} else {
						reject()
					}
				}).catch(() => {
					reject()
				})
			} else {
				var ajaxData = {
					tag: store.state.$tag,
					terminalCode,
					is_publish: '0',
					terminalVersion: store.state.$dVersion,
					interpreterCode: store.state.$parserVer,
					t: new Date().getTime()
				}
				return ajax({
					moduleUrl: '1',
					url: '/getLastVersion2',
					method: 'get',
					noErrorMsg: true,
					data: ajaxData
				}).then(res => {
					if (res.code == 200) {
						var targetVersion = res.data.interpreter_last_version
						if (targetVersion) {
							resolve({
								version: targetVersion.version,
								appInfo: JSON.parse(targetVersion.app_info || '{}'),
								skin: {
									skinIcon: JSON.parse(targetVersion.skin_icon ||
										'[]'),
									cdnUrl: targetVersion.url,
									skinVersion: targetVersion.skin_version
								}
							})
						} else {
							reject()
						}
					} else {
						reject()
					}
				}).catch(() => {
					reject()
				})
			}
		}).then(targetVersion => {
			// 保存最新版本信息
			vuexSave('$version', targetVersion.version)
			// 保存最新启动信息
			var appInfo = targetVersion.appInfo;
			vuexSave('$appInfo', appInfo);
			// 保存最新皮肤的图标坐标信息
			var icons = targetVersion.skin.skinIcon;
			vuexSave('$icons', getIcons(icons));
			// 保存页面列表、预览模式、运行环境等
			if (config.development === 'prod') {
				vuexSave('$pageList', targetVersion.pageList);
				vuexSave('$prevMode', false);
				vuexSave('$development', 'prod');
			} else {
				vuexSave('$prevMode', true)
				vuexSave('$development', appInfo.development);
			}
			var skinUrl = targetVersion.skin.cdnUrl;
			var skin_version = targetVersion.skin.skinVersion;
			if(config.development === 'prod' && ifFileManage){
				// 采用文件管理
				// 根据皮肤的版本号来判断是否需要更新皮肤文件
				fs.readFile({
					filePath: `${userDataPath}/skin_info.txt`,
					encoding: 'utf8',
					success(res) {
						console.log('readFile-success', 'skin_info.txt', res.data);
						var skin_info = res.data.split(',');
						var oldSkinVersion = skin_info[0]*1;
						if (oldSkinVersion === skin_version) {
							// 如果皮肤版本未更新：不下载皮肤，进入下一步
							console.log('皮肤版本未更新', oldSkinVersion, skin_version);
							vuexSave('$skinUrl', `${userDataPath}/skin.png`);
							vuexSave('$skinW', skin_info[1]*1);
							vuexSave('$skinH', skin_info[2]*1);
							getAppStartPage().then(appMenus=>{
								resolve(appMenus)
							})
						} else {
							// 如果皮肤版本更新了：下载皮肤，并记录皮肤版本
							console.log('皮肤版本更新了', oldSkinVersion, skin_version);
							downSkin(skin_version, skinUrl).finally(() => {
								getAppStartPage().then(appMenus=>{
									resolve(appMenus)
								})
							})
						}
					},
					fail(res) {
						console.log('readFile-fail', res)
						downSkin(skin_version, skinUrl).finally(() => {
							getAppStartPage().then(appMenus=>{
								resolve(appMenus)
							})
						})
					}
				})
			}else{
				// 不采用文件管理：兼容方法
				// #ifdef MP-ALIPAY
				var oldSkinVersion = store.state.$skinVersion;
				if(oldSkinVersion){
					if (oldSkinVersion === skin_version) {
						// 如果皮肤版本未更新：不下载皮肤，进入下一步
						console.log('皮肤版本未更新', oldSkinVersion, skin_version);
						resolve()
					}else{
						// 如果皮肤版本更新了：下载皮肤，并记录皮肤版本
						console.log('皮肤版本更新了', oldSkinVersion, skin_version);
						downSkin(skin_version, skinUrl).finally(() => {
							resolve()
						})
					}
				}else{
					// 如果读取皮肤版本失败：下载皮肤，并记录皮肤版本
					console.log('读取皮肤版本失败');
					downSkin(skin_version, skinUrl).finally(() => {
						resolve()
					})
				}
				// #endif
				// #ifndef MP-ALIPAY
				if (store.state.$skinUrl === skinUrl && store.state.$skinW > 0 && store.state.$skinH > 0) {
					console.log('获取缓存的图片尺寸,皮肤尺寸为', store.state.$skinW, store.state.$skinH);
				} else {
					getSkinSize(skinUrl)
				}
				resolve()
				// #endif
			}
		}, () => {
			reject()
		})
	})
}